{% extends "ceudp/base.html" %}
{% load staticfiles %}

{% block customize-style %}
    <style type="text/css">
        div.dataTables_filter {
            text-align: left;
        }
    </style>
{% endblock %}

{% block customize-script %}
<script>
    leaf_active("groups"); // 激活左侧菜单栏图标效果
    $.ajaxSetup({
        data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
    });

    var group_table = null;
    var group_permission_select = null;
    var modified_group_permission_select = null;
    var permissions = null;
    $.ajax({
        type: "GET",
        url: "{% url 'management_api:permission-list' %}",
        async: false,
        success: function(response){
            var data = [];
            for (var i = 0; i < response.length; i++) {
                data[i] = {
                    id: response[i].id,
                    text: response[i].name,
                };
            }

            permissions = data;
        },
        error: function(response){
            sweetAlert("错误", response.responseText, "error");
        },
    });

    $(function(){
        group_table = $('#group_table').DataTable({
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "paginate": {
                    "first": "第一页",
                    "previous": "上一页",
                    "next": "下一页",
                    "last": "最后一页",
                },
            },
            "info": true,
            "paging": true,
            // "searching": false,
            "autoWidth": false,
            "processing": true,
            "bLengthChange": false, // 是否启动可以改变单页数量
            "iDisplayLength" : 20, // 设置单页显示数量
            "order": [[ 0, "asc" ]], // 默认 按第4列（从0开始）倒序排列
            "ajax": {
                "url": "{% url 'management_api:group-list' %}",
                "method": "GET",
                "timeout": 5000,
                "dataSrc": function(response){ return response },
                "error": function(response){
                    sweetAlert("错误", response.responseText, "error");
                },
            },
            "columns": [
                { 
                    "data": "id", "title": "编号",
                    "render": function(id){
                        var html = "<a href='#' data-toggle='modal' data-target='#group-modified-modal' onclick=show_group_modify(" + id + ")>" + 
                                id + 
                            "</a>";
                         return html;
                    },
                },
                { 
                    "data": "name", "title": "用户组名称",
                },
            ],
            "dom": "<'#top-search.pull-left' f> <'#top-toolbar'>rtip",

        });

        // 顶部按钮
        var top_toolbar = "<div>" +
            "<div class='btn-group pull-right'>" +
                "<button type='button' class='btn btn-danger btn-sm' data-toggle='modal' data-target='#group-create-modal'>" + 
                    "<i class='fa fa-group'></i>" +
                "</button>" +
            "</div>" +
        "</div>";
        $("#top-toolbar").html(top_toolbar);

        permission_select = $(".permissions").select2({
            data: permissions,
            placeholder:"  请选择",//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true//允许清空
        });
    });

    $("#create-btn").on("click", function(){
        var create_data = {
            "name": $("#create-group").val(),
            "permissions": [],
        }

        var permission_vals = permission_select.val();
        if (permission_vals != null) {
            create_data["permissions"] = permission_vals;
        } 

        $.ajax({
            type: "POST",
            url: "{% url 'management_api:group-list' %}",
            data: JSON.stringify(create_data),
            async: false,
            contentType: "application/json",
            success: function(response){
                sweetAlert("创建用户组成功", "", "success");
                group_table.ajax.reload();
            },
            error: function(response){
                sweetAlert("错误", response.responseText, "error");
            },
        });

        $("#create-close-btn").click();
    });
    
    $("#modified-btn").on("click", function(){
        var modified_data = {
            "name": $("#modified-name").val(),
        }

        var modified_permission_vals = modified_permission_select.val();
        if (modified_permission_vals != null) {
            modified_data["permissions"] = modified_permission_vals;
        }

        console.info(modified_data);
        $.ajax({
            type: "PATCH",
            url: "/api/management/groups/" + $("#modified-id").val() + "/",
            data: JSON.stringify(modified_data),
            contentType: "application/json",
            async: false,
            success: function(response){
                sweetAlert("修改用户组成功", "", "success");
                group_table.ajax.reload();
            },
            error: function(response){
                sweetAlert("错误", response.responseText, "error");
            },
        });

        $("#modified-close-btn").click();
    });

    function show_group_modify(id) {
        modified_permission_select = $(".modified-permissions").select2({
            data: permissions,
            placeholder:"  请选择",//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true//允许清空
        });

        $.ajax({
            type: "GET",
            url: "/api/management/groups/" + id + "/",
            async: false,
            success: function(response){
                $("#modified-id").val(response.id);
                $("#modified-name").val(response.name);
                modified_permission_select.val(response.permissions).trigger("change");
            },
            error: function(){
                sweetAlert("错误", response.responseText, "error");
            },
        });
    }

</script>
{% endblock %}

{% block content %}
<div class="content-wrapper">
    <section class="content-header">
        <h1><i class="fa fa-group"></i> 用户组管理<small>User Management</small></h1>
        <ol class="breadcrumb">
            <li><a href="{% url 'dashboard:index' %}"><i class="fa fa-dashboard"></i> 仪表盘 <small>[Dashboard]</small> </a></li>
            <li><a href="#"><i class="fa fa-sliders"></i>系统管理 <small>[Management]</small></a></li>
            <li class="active"><i class="fa fa-group"></i> 用户组管理 <small>[Groups]</small></li>
        </ol>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">用户组列表</h3>
                    </div>
                    <div class="box-body">
                        <table id="group_table" class="table">
                            <thead>
                                <tr>
                                    <th>id</th>
                                    <th>name</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="modal fade" id="group-create-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title"><i class="fa fa-group"></i> 用户组创建</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户组名</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="create-group" placeholder="用户组名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="permissions" class="col-sm-2 control-label">权限</label>
                            <div class="col-sm-9">
                                <select class="permissions" multiple="multiple" style="width: 100%;"></select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger pull-left" data-dismiss="modal" id="create-close-btn">关闭</button>
                    <button type="button" class="btn btn-success" id="create-btn">创建</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="group-modified-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title"><i class="fa fa-group"></i> 修改用户组</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户编号</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="modified-id" placeholder="用户组编号" disabled>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户组名</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="modified-name" placeholder="用户组名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="modified-permissions" class="col-sm-2 control-label">权限</label>
                            <div class="col-sm-9">
                                <select class="modified-permissions" multiple="multiple" style="width: 100%;"></select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger pull-left" data-dismiss="modal" id="modified-close-btn">关闭</button>
                    <button type="button" class="btn btn-success" id="modified-btn">修改</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}